package br.com.cfccultura.admin.control.actions.cadastros;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.stereotype.Component;

import br.com.cfccultura.admin.control.actions.DefaultAction;
import br.com.cfccultura.admin.control.forms.cadastros.CadastroCalendarioForm;
import br.com.cfccultura.admin.model.enums.DiaSemana;
import br.com.cfccultura.admin.model.enums.SimNao;
import br.com.cfccultura.admin.model.vo.CalendarioDia;

@Component("/cadastroCalendario")
public class CadastroCalendarioAction extends DefaultAction {
	
	private static final Logger logger = Logger.getLogger(CadastroCalendarioAction.class);	
	
	public ActionForward iniciar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		consultar(calendarioForm, request);
		
		return mapping.findForward("body");
	}
	
	public ActionForward consultar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		consultar(calendarioForm, request);
		
		return mapping.findForward("body");
	}
	
	private void consultar(CadastroCalendarioForm calendarioForm, HttpServletRequest request) {
		CalendarioDia vo = new CalendarioDia();		
		List<CalendarioDia> listaResultado = getCalendarioDAO().consultar(vo);
		request.setAttribute("listaResultado", listaResultado);
	}
	
	public ActionForward incluir(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		CalendarioDia vo = new CalendarioDia();
		vo.setData(getDateFormat().parse(calendarioForm.getData()));
		vo.setDescricao(calendarioForm.getDescricao());
		vo.setFeriado(SimNao.setValue(calendarioForm.getFeriado()));
		vo.setUsuarioSistema(getUsuario(request));
		
		getCalendarioDAO().incluir(vo);
		
		return null;
	}
	
	
	public ActionForward verificaData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		Date dataInformada = getDateFormat().parse(calendarioForm.getData());
		
		CalendarioDia vo = getCalendarioDAO().consultar(dataInformada);
		
		Object[] params = {};
		if(vo != null) {
			params = new Object[]{
				false,
				"Data já cadastrada no Calendário!"
			};
		} else {
			params = new Object[]{
				true
			};
		}
		
		printJsonObjectToStream(params, response);
		
		return null;
	}	
	
	public ActionForward alterarIniciar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		CalendarioDia vo = getCalendarioDAO().consultar(calendarioForm.getIdSelecionado());
		
		Object[] params = {
			getDateFormat().format(vo.getData()),
			vo.getFeriado().getValue(),
			vo.getDescricao()
		};
		
		printJsonObjectToStream(params, response);
		
		return null;
	}
	
	public ActionForward alterar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		CalendarioDia vo = new CalendarioDia();
		vo.setCodigo(calendarioForm.getIdSelecionado());
		
		vo.setData(getDateFormat().parse(calendarioForm.getData()));
		vo.setDescricao(calendarioForm.getDescricao());
		vo.setFeriado(SimNao.setValue(calendarioForm.getFeriado()));
		vo.setUsuarioSistema(getUsuario(request));

		getCalendarioDAO().alterar(vo);
		
		return null;
	}
	
	
	public ActionForward carregar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {		
		
		CadastroCalendarioForm calendarioForm = (CadastroCalendarioForm) form;
		
		Date dataInicial = getDateFormat().parse("01/01/2012");
		Calendar c = Calendar.getInstance();
		c.setTime(dataInicial);
		
		List<CalendarioDia> dias = getCalendarioDAO().consultar(new CalendarioDia());
		if(dias.size() > 0) {
			CalendarioDia dia = dias.get(dias.size() - 1);
			c.setTime(dia.getData());
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		Calendar d = Calendar.getInstance();
		d.setTime(c.getTime());
		d.set(Calendar.DAY_OF_MONTH, 31);
		d.set(Calendar.MONTH, 11);
		
		for(int i=0;i<500;i++) {
			
			CalendarioDia dia = new CalendarioDia();
			dia.setData(c.getTime());
			
			String descricao = consultaFeriado(dia.getData());
			
			dia.setDescricao(descricao);
			dia.setDiaSemana(DiaSemana.setValue(c.get(Calendar.DAY_OF_WEEK)));
			dia.setFeriado(descricao.equals("") ? SimNao.NAO : SimNao.SIM);
			dia.setUsuarioSistema(getUsuario(request));
			
			getCalendarioDAO().incluir(dia);
			System.out.println("Dia -> " + getDateFormat().format(dia.getData()) + " - " + dia.getDescricao());
			
			if(getDateFormat().format(c.getTime()).equals(getDateFormat().format(d.getTimeInMillis())))
				break;
			
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		System.out.println("Carga Completa!");
		
		return null;
	}
	
	private String consultaFeriado(Date data) throws Exception {
		HashMap<String, String> lista = getListaFeriados();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM");
		if(lista.containsKey(sdf.format(data.getTime()))) {
			return lista.get(sdf.format(data.getTime()));
		}
		return "";
	}
	
	private HashMap<String, String> getListaFeriados() throws Exception {
		HashMap<String, String> lista = new HashMap<String, String>();
		lista.put("01/01", "Ano Novo");
		lista.put("20/02", "Carnaval");
		lista.put("21/02", "Carnaval");
		lista.put("22/02", "Carnaval");
		lista.put("06/04", "Paixão de Cristo");
		lista.put("21/04", "Tiradentes");
		lista.put("01/05", "Dia do Trabalho");
		lista.put("07/06", "Corpus Christi");
		lista.put("07/09", "Indenpendência do Brasil");
		lista.put("12/10", "Nossa Senhora Aparecida");
		lista.put("02/11", "Finados");
		lista.put("15/11", "Proclamação da República");
		lista.put("24/12", "Véspera de Natal");
		lista.put("25/12", "Natal");
		lista.put("31/12", "Véspera de Ano Novo");
		return lista;
	}
}
